package cn.szzsi.service;

import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.model.SiteConfig;
import com.jfinal.kit.StrKit;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by admin on 2017/1/18.
 */
public class FileService {

    //时间、名称、大小、类型
    public enum SortType {
        time, name, size, type
    }

    public static FileService fs = new FileService();


    public String getShopFileRoot(String shopId){
        String shopalias = SiteConfig.dao.getShopAliasByShopId(shopId);
        if(StrKit.notBlank(shopalias)){
            return File.separator+"upload"+ File.separator+shopalias+ File.separator;
        }

        return SystemConfig.UPLOAD_IMAGE_DIR;
    }

    public void sortFiles(File[] files, String sortType){
        if(sortType.equalsIgnoreCase(SortType.name.name())){
		    Arrays.sort(files,new FileService.sortByName());
        }else if(sortType.equalsIgnoreCase(SortType.size.name())){
		    Arrays.sort(files,new FileService.sortBySize());
        }else if(sortType.equalsIgnoreCase(SortType.type.name())){
		    Arrays.sort(files,new FileService.sortByName());
        }else{
		    Arrays.sort(files,new FileService.sortByTime());
        }
    }

    public static class sortBySize implements Comparator<File>
    {
        public int compare(File f1, File f2) {
            long diff = f2.length() - f1.length();
            if (diff > 0)
                return 1;
            else if (diff == 0)
                return 0;
            else
                return -1;
        }
        public boolean equals(Object obj){
            return true;
        }
    }
    public static class sortByName implements Comparator<File>
    {
        public int compare(File f1, File f2) {
            if (f2.isDirectory() && f1.isFile())
                return -1;
            if (f2.isFile() && f1.isDirectory())
                return 1;
            return f2.getName().compareTo(f1.getName());
        }
        public boolean equals(Object obj){
            return true;
        }
    }
    public static class sortByTime implements Comparator<File>
    {
        public int compare(File f1, File f2) {
            long diff = f2.lastModified()-f1.lastModified();
            if(diff>0) {
                return 1;
            } else if(diff==0)
                return 0;
            else
                return -1;
        }
        public boolean equals(Object obj){
            return true;
        }
    }

}
